package demo.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Calendar;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import demo.servlet.util.ContentType;

/**
 * Servlet implementation class JDBCServlet
 */
public class JDBCServlet extends HttpServlet {

    private static final long serialVersionUID = 1632324304313744399L;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        // Obtain our environment naming context
        String message = "JDBC connection works good!";

        try {
            Context initCtx = new InitialContext();

            Context envCtx = (Context) initCtx.lookup("java:comp/env");

            // Look up our data source
            DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");

            // Allocate and use a connection from the pool
            Connection conn = ds.getConnection();

            // ... use this connection to access the database ...
            conn.close();
        } catch (NamingException e) {
            message = e.getMessage();
            // TODO Auto-generated catch block
            e.printStackTrace();

        } catch (SQLException e) {
            message = e.getMessage();
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        response.setContentType(ContentType.HTML);
        PrintWriter out = response.getWriter();
        out.println(message);
        out.println("<br />");
        out.println(Calendar.getInstance().getTime().toString());
        out.flush();
        return;
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        // TODO Auto-generated method stub
    }

}
